package com.stoken.web.control;

import java.io.IOException;
import java.text.ParseException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.stoken.domain.MemberAchievement;
import com.stoken.domain.MemberBaseInfo;
import com.stoken.domain.MemberLeaveMessage;
import com.stoken.domain.MemberRegisterInfo;
import com.stoken.domain.Notice;
import com.stoken.domain.TravelLeaveMessage;
import com.stoken.service.BonusCalculationService;
import com.stoken.service.LineUseService;
import com.stoken.service.MemberAchievementService;
import com.stoken.service.MemberBaseInfoService;
import com.stoken.service.MemberLeaveMessageService;
import com.stoken.service.MemberRegisterInfoService;
import com.stoken.service.NoticeService;
import com.stoken.service.TravelLeaveMessageService;
import com.stoken.service.impl.MemberExtractListServiceImpl;
import com.stoken.web.StokenUtils;
import com.symbio.commons.Compositor;
import com.symbio.commons.Compositor.CompositorType;
import com.symbio.commons.Page;
import com.symbio.utils.EncryptUtils;

@Controller
@RequestMapping("/login")
public class LoginControl {
	
	@Autowired
	private MemberBaseInfoService mbBaseInfoService;
	
	@Autowired
	private MemberRegisterInfoService memberRegisterService;
	
	@Autowired
	private NoticeService noticeService;
	
	@Autowired
	private MemberLeaveMessageService memberLeaveMessageService;
	
	@Autowired
	private TravelLeaveMessageService travelLeaveMessageService;
	
	@Autowired
	private MemberAchievementService memberAchievementService;
	
	@Autowired
	private BonusCalculationService bonusCalculation;
	
	@Autowired
	private LineUseService lineUseService;
    
	private Logger logger  = Logger.getLogger(LoginControl.class);
	
	@RequestMapping(method=RequestMethod.GET)
	public String loadLoginPage(){
		return "/login";		
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String loadLoginPageB(){
		return "/login";	
	}
	
	@RequestMapping(value="/backstage")
	public String loadAdminLoginPage(){
		return "/backstage/login";		
	}
	
	@RequestMapping("/backstage/validate")
	public String adminLogin(HttpServletRequest request,ModelMap modeMape){
		//等到用户输入的用户名
		String account = request.getParameter("account").trim();
		String password = request.getParameter("password");
        String code = request.getParameter("code").toUpperCase();
        
        logger.info("会员登录，登录会员名："+account);
		
		String volidate = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);		
		if(!StringUtils.equals(volidate, code))
		{
			request.setAttribute("error", "0");
			return "/backstage/login";
		}
		if(StringUtils.isNotBlank(account)){		
			if(account.equals("fradmin") && password.equals("adminfr201")){
				request.getSession().setAttribute(StokenUtils.ACCESS_ROLE, StokenUtils.ADMIN_ACCESS_ROLE);
				request.getSession().setAttribute(StokenUtils.LOGINACCOUNT, account);
				return "/backstage/index";		
			}
				
		}
		
		return "/backstage/login";
	}
	
	@RequestMapping(value="/merchant")
	public String loadAdminLoginMerchant(){
		return "/merchant/login2";		
	}
	
	@RequestMapping("/merchant/validate")
	public String adminLoginMerchant(HttpServletRequest request,ModelMap modeMape){
		//等到用户输入的用户名
		String account = request.getParameter("account").trim();
		String password = request.getParameter("password");
		
		if(StringUtils.isNotBlank(account)){		
			if(StringUtils.equals(account, "eatw") && StringUtils.equals(password, "eatw888atw")){
				request.getSession().setAttribute(StokenUtils.ACCESS_ROLE, StokenUtils.SERVICE_PROVIDERS_ACCESS_ROLE);
				request.getSession().setAttribute(StokenUtils.LOGINACCOUNT, account);
				return "/merchant/index";		
			}	
		}
		return "/merchant/login";
	}
	
	
	@RequestMapping("/validate")
	public String login(HttpServletRequest request,ModelMap modeMape){
		//等到用户输入的用户名
		String account = request.getParameter("account").trim();
		String password = request.getParameter("password");
		String code = request.getParameter("code").toUpperCase();
		
		String volidate = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);		
		if(!StringUtils.equals(volidate, code))
		{
			request.setAttribute("error", "0");
			return "/login";
		}
		
		if(StringUtils.isNotBlank(account)){
			MemberBaseInfo memberBaseInfo = mbBaseInfoService.verificationLogin(account, EncryptUtils.md5(password));
			if(memberBaseInfo != null){
				request.getSession().setAttribute(StokenUtils.ACCESS_ROLE, StokenUtils.ACCESS_ROLE);
				request.getSession().setAttribute(StokenUtils.LOGINACCOUNT, memberBaseInfo);
				//查询注册等级
				MemberRegisterInfo register = memberRegisterService.findRegisterByUserName(memberBaseInfo.getBaseUsername());
				request.getSession().setAttribute(StokenUtils.REGISTERGRADE, register.getRegisterGrade());
				
				//查询公告
			    Page<Notice> noticePage = new Page<Notice>();
			    noticePage.getPagination().setPageSize(8);
				Compositor compositor = new Compositor("createTime",CompositorType.DESC);
				noticePage.setCompositor(compositor);
				noticePage = noticeService.find(noticePage);
				request.setAttribute("noticePage", noticePage);
				
				//查询留言
				Page<MemberLeaveMessage> leavePage = new Page<MemberLeaveMessage>();
				leavePage.getPagination().setPageSize(8);
				compositor = new Compositor("leaveTime",CompositorType.DESC);
				leavePage.setCompositor(compositor);
				leavePage = memberLeaveMessageService.find(leavePage,memberBaseInfo.getId());	
				request.setAttribute("leavePage", leavePage);
				
				//查询旅游留言
				Page<TravelLeaveMessage> travelPage = new Page<TravelLeaveMessage>();
				compositor = new Compositor("leaveTime",CompositorType.DESC);
				travelPage.setCompositor(compositor);
				travelPage = travelLeaveMessageService.find(travelPage,memberBaseInfo.getId());
				request.setAttribute("travelPage", travelPage);
				
				//查询业绩
				MemberAchievement achieve = memberAchievementService.findSelf(memberBaseInfo.getId());
				request.getSession().setAttribute("achieve", achieve);
				return "/index";					
			}else{
				request.setAttribute("error", "1");
			}
		}
		
		return "/login";
	}
	
	@RequestMapping("/findSelf")
	@ResponseBody  
	public MemberAchievement findSelfAchievement(HttpServletRequest request,ModelMap modeMape){
		MemberBaseInfo memberBaseInfo = (MemberBaseInfo)request.getSession().getAttribute(StokenUtils.LOGINACCOUNT);
		MemberAchievement achieve = memberAchievementService.findSelf(memberBaseInfo.getId());
		return achieve;
	}
	
	@RequestMapping("/secondPwd")
	public String secondPwd(HttpServletRequest request,ModelMap modeMape){
		return "secondPassword";
	}
	
	@RequestMapping("/thirdPwd")
	public String thirdPwd(HttpServletRequest request,ModelMap modeMape){
		return "thirdPwd";
	}
	
	@RequestMapping("/inputSecondPwd")
	public String inputSecondPwd(HttpServletRequest request,HttpServletResponse response,ModelMap modeMape,String pwd){
		 MemberBaseInfo mbi = (MemberBaseInfo)request.getSession().getAttribute(StokenUtils.LOGINACCOUNT);
		 if(StringUtils.equals(EncryptUtils.md5(pwd), mbi.getBasePasswordSeconde()))
		 {
			 try {
				request.getSession().setAttribute(StokenUtils.ACCESS_SECOND_PWD, StokenUtils.ACCESS_SECOND_PWD); 
				response.sendRedirect(request.getSession().getAttribute(StokenUtils.PARENT_URL).toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
			 return null;
		 }else
		 {
			 request.setAttribute("error", "密码输入错误");
			 return "secondPassword";
		 }
	}
	
	@RequestMapping("/inputThirdPwd")
	public String inputThirdPwd(HttpServletRequest request,HttpServletResponse response,ModelMap modeMape,String pwd){
		 MemberBaseInfo mbi = (MemberBaseInfo)request.getSession().getAttribute(StokenUtils.LOGINACCOUNT);
		 if(StringUtils.equals(EncryptUtils.md5(pwd), mbi.getBasePasswordThird()))
		 {
			 try {
				request.getSession().setAttribute(StokenUtils.ACCESS_THIRD_PWD, StokenUtils.ACCESS_THIRD_PWD); 
				response.sendRedirect(request.getSession().getAttribute(StokenUtils.PARENT_THIRD_URL).toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
			 return null;
		 }else
		 {
			 request.setAttribute("error", "密码输入错误");
			 return "thirdPwd";
		 }
	}
	
	
	
	@RequestMapping("/exit")
	public String exit(HttpServletRequest request){
		request.getSession().invalidate();
		return "/login";
	}
	
	@RequestMapping("/starBonus")
	public void startExecutBonus(){
		try {
			bonusCalculation.starSystemService();
		} catch (SchedulerException e) {			
			e.printStackTrace();
		} catch (ParseException e) {			
			e.printStackTrace();
		}
	}
	
	/*@RequestMapping("/error")
	public void bringPsw(){
		bonusCalculation.initdata();
	}*/
	
	@RequestMapping("/initLineUse")
    public void init(){
    	lineUseService.init();
    }
	
	
}
